﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace Zero.UControl.Demo.Views
{
    /// <summary>
    /// TriangleLoading2.xaml 的交互逻辑
    /// </summary>
    public partial class TriangleLoading2 : UserControl
    {
        public TriangleLoading2()
        {
            InitializeComponent();
        }

        public double CurrentValue
        {
            get { return (double)GetValue(CurrentValueProperty); }
            set { SetValue(CurrentValueProperty, value); }
        }

        public static readonly DependencyProperty CurrentValueProperty =
            DependencyProperty.Register("CurrentValue", typeof(double), typeof(TriangleLoading2), new PropertyMetadata(0d, OnCurrentValueChanged));

        private static void OnCurrentValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            double oldValue = (double)e.OldValue;
            double newValue = (double)e.NewValue;
            if(newValue != oldValue)
            {
                (d as TriangleLoading2)?.UpdateProgress(newValue);
            }
        }

        private void UpdateProgress(double targetProgress)
        {
            if (ProgressPath.StrokeThickness == 0) return;
            if (targetProgress < 0 || targetProgress > 100)
                throw new ArgumentOutOfRangeException("参数范围错误");

            ProgressText.Text = targetProgress.ToString("N0") + "%";
            ProgressPath.StrokeDashArray = new DoubleCollection { targetProgress, double.MaxValue };
        }

        private double GetTotalLength()
        {
            double totalLength = 0d;
            if (ProgressPath.Data is not PathGeometry geometry)
            {
                return totalLength;
            }
       
            foreach (var figure in geometry.Figures)
            {
                Point start = figure.StartPoint;
                foreach (var sg in figure.Segments)
                {
                    if (sg is LineSegment lsg)
                    {
                        totalLength += (lsg.Point - start).Length;
                        start = lsg.Point;
                    }
                }
            }
            return totalLength;
        }
    }
}
